/**
 * 
 */
package com.suyx.job.config;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baidu.aip.ocr.AipOcr;
import com.suyx.job.utils.Base64Util;
import com.suyx.job.utils.FileUtil;
import com.suyx.job.utils.HttpUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author syx
 *
 */
@Slf4j
@Component
public class BaiduOCR {
	//设置APPID/AK/SK
    public static final String APP_ID = "16353031";
    public static final String API_KEY = "GlHbe8dzxGBneyjwSQh4pDAC";
    public static final String SECRET_KEY = "VCebnzaPyurv9mG665T3jT9GyElvoMci";
    
    @Autowired
    private RedisUtils redis;
	
    public  String sampleAccurate(String addrImg) throws InterruptedException {
    	AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("probability", "true");

        Thread.sleep(1000l);
        JSONObject res = client.basicAccurateGeneral(addrImg, options);
        try {
        	JSONArray ja = res.getJSONArray("words_result");
        	if(ja.length() == 0){
        		return "";
        	}
            JSONObject jo = ja.getJSONObject(0);
            return  jo.getString("words");
		} catch (JSONException e) {
			e.printStackTrace();
			return "";
		}
    }
    
    public  String sampleBasic(String addrImg) throws InterruptedException {
    	AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
	    options.put("detect_direction", "true");
	    options.put("detect_language", "true");
	    options.put("probability", "true");

	    Thread.sleep(1000l);
        JSONObject res = client.basicGeneral(addrImg, options);
        try {
        	JSONArray ja = res.getJSONArray("words_result");
        	if(ja.length() == 0){
        		return "";
        	}
            JSONObject jo = ja.getJSONObject(0);
            return  jo.getString("words");
		} catch (JSONException e) {
			e.printStackTrace();
			return "";
		}
    }
    /**
     * 获取权限token
     * @return 返回示例：
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    private  String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = API_KEY;
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = SECRET_KEY;
        String ocr_Token = (String) redis.get("ocr_auth");
        if (StringUtils.isEmpty(ocr_Token)) {
        	ocr_Token = getAuth(clientId, clientSecret);
        	redis.set("ocr_auth", ocr_Token,2572L);
        }
        return ocr_Token;
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    private  String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            /*URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }*/
            /**
             * 返回结果示例
             */
        	log.info("requestToken:" + getAccessTokenUrl);
        	String result = cn.hutool.http.HttpUtil.get(getAccessTokenUrl);
            log.info("responToken:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    public  String generalBasic(String filePath) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        try {
            // 本地文件路径
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth();

           // log.info("通用文字识别接口请求:"+param);
           // String result = HttpUtil.post(url, accessToken, param);
            String result = cn.hutool.http.HttpUtil.post(url+"?access_token=" + accessToken, param);
            log.info("通用文字识别接口返回:"+result);
            try {
            	JSONObject jsonObject = new JSONObject(result);
            	JSONArray ja = jsonObject.getJSONArray("words_result");
            	StringBuffer str = new StringBuffer();
            	for(int i=0;i<ja.length();i++){
            		str.append(ja.getJSONObject(i).getString("words"));
            	}
                return  str.toString();
    		} catch (JSONException e) {
    			e.printStackTrace();
    			return "";
    		}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public  String generalBasicMoveOne(String filePath) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        try {
            // 本地文件路径
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth();

            //String result = HttpUtil.post(url, accessToken, param);
            String result = cn.hutool.http.HttpUtil.post(url+"?access_token=" + accessToken, param);
            log.info("通用文字识别接口返回:"+result);
            try {
            	JSONObject jsonObject = new JSONObject(result);
            	JSONArray ja = jsonObject.getJSONArray("words_result");
            	StringBuffer str = new StringBuffer();
            	for(int i=0;i<ja.length();i++){
            		String st = ja.getJSONObject(i).getString("words");
            		if(StringUtils.isNotEmpty(st) && st.indexOf("D") > -1){
            			continue;
            		}
            		str.append(st);
            	}
                return  str.toString();
    		} catch (JSONException e) {
    			e.printStackTrace();
    			return "";
    		}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public  String getBestAnimal(String filePath,String roleName) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        try {
            // 本地文件路径
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth();

            log.info("通用文字识别接口返回师门最优宠物接口请求:"+param);
            //String result = HttpUtil.post(url, accessToken, param);
            String result = cn.hutool.http.HttpUtil.post(url+"?access_token=" + accessToken, param);
            log.info("通用文字识别接口返回师门最优宠物:"+result);
            try {
            	JSONObject jsonObject = new JSONObject(result);
            	JSONArray ja = jsonObject.getJSONArray("words_result");
            	Map<Integer,String> map = new HashMap<>();
            	Integer[] att = new Integer[5];
            	map.put(Integer.valueOf(ja.getJSONObject(0).getString("words")), "身强体壮");
            	map.put(Integer.valueOf(ja.getJSONObject(1).getString("words")), "法力高深");
            	map.put(Integer.valueOf(ja.getJSONObject(2).getString("words")), "武力超群");
            	map.put(Integer.valueOf(ja.getJSONObject(3).getString("words")), "刀枪不入");
            	map.put(Integer.valueOf(ja.getJSONObject(4).getString("words")), "身手灵敏");
            	
            	String strB_or = (String) redis.get("bestAnimal"+roleName);
            	String is_continue = "no@";
            	StringBuffer strB =  new StringBuffer();
            	strB.append(ja.getJSONObject(0).getString("words"))
	            	.append(ja.getJSONObject(1).getString("words"))
	            	.append(ja.getJSONObject(2).getString("words"))
	            	.append(ja.getJSONObject(3).getString("words"))
	            	.append(ja.getJSONObject(4).getString("words"));
            	if(StringUtils.isNoneBlank(strB_or) && strB_or.equals(strB.toString())){
            		is_continue = "yes@";
            	}
            	log.info("判定是否宠物为同一个:"+roleName + "==>" + strB_or + ":" +strB.toString());
            	redis.set("bestAnimal"+roleName,strB.toString());
            	
            	for(int i=0;i<ja.length();i++){
            		att[i] = Integer.valueOf(ja.getJSONObject(i).getString("words"));
            	}
            	for(int i=0 ;i<5;i++){
             	   for(int j=i+1 ;j<5;j++){
             		   if(att[i]< att[j]){
             			   int t = att[i];
             			   att[i] = att[j];
             			   att[j] = t;
             		   }
             	   }
                }
            	StringBuffer returnStr = new StringBuffer();
            	if(att.length > 2){
            		returnStr.append(map.get(att[0])).append("&");
            		if(att[1] == att[2]){
                        return is_continue + returnStr.toString();
            		}else{
            			returnStr.append(map.get(att[1]));
            		}
            	}
                return  is_continue + returnStr.toString();
    		} catch (JSONException e) {
    			e.printStackTrace();
    			return "";
    		}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    public  String accurateBasic(String filePath) {
    	// 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        try {
            // 本地文件路径
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth();

            //String result = HttpUtil.post(url, accessToken, param);
            log.info("通用文字识别接口请求（高精度版）:"+param);
            String result = cn.hutool.http.HttpUtil.post(url+"?access_token=" + accessToken, param);
            log.info("通用文字识别接口返回（高精度版）:"+result);
            try {
            	JSONObject jsonObject = new JSONObject(result);
            	JSONArray ja = jsonObject.getJSONArray("words_result");
            	StringBuffer str = new StringBuffer();
            	for(int i=0;i<ja.length();i++){
            		str.append(ja.getJSONObject(i).getString("words"));
            	}
                return  str.toString();
    		} catch (JSONException e) {
    			e.printStackTrace();
    			return "";
    		}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    	
    }
}
